package com.zhangxu.microservice.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AesEncryptUtils {

    private static SecretKeySpec keySpec;
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 设置加密密钥（Base64 格式）
     */
    public static void setKey(String base64Key) {
        byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        if (keyBytes.length != 32) {
            throw new IllegalArgumentException("AES密钥必须为256位（32字节）");
        }
        keySpec = new SecretKeySpec(keyBytes, "AES");
    }

    /**
     * 加密
     */
    public static String encrypt(String plainText) {
        if (keySpec == null) {
            throw new IllegalStateException("请先初始化 AES Key");
        }
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("AES 加密失败", e);
        }
    }

    /**
     * 解密
     */
    public static String decrypt(String cipherText) {
        if (keySpec == null) {
            throw new IllegalStateException("请先初始化 AES Key");
        }
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decoded = Base64.getDecoder().decode(cipherText);
            byte[] decrypted = cipher.doFinal(decoded);
            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("AES 解密失败", e);
        }
    }
}
